package com.suke.czx.modules.oss.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.suke.czx.common.annotation.AuthIgnore;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.exception.RRException;
import com.suke.czx.common.utils.FilezUtils;
import com.suke.czx.modules.oss.cloud.ICloudStorage;
import com.suke.czx.modules.oss.entity.SysOss;
import com.suke.czx.modules.oss.service.SysOssService;
import com.suke.zhjg.common.autofull.util.R;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 文件上传
 *
 * @author developer
 * @date 2025-05-13 12:13:26
 */
@Slf4j
@RestController
@RequestMapping("sys/oss")
@AllArgsConstructor
@Api(value = "SysOssController", tags = "文件上传")
public class SysOssController extends AbstractController {

    private final SysOssService sysOssService;
    private final ICloudStorage iCloudStorage;



    /**
     * 列表
     */
    @GetMapping(value = "/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        QueryWrapper<SysOss> queryWrapper = new QueryWrapper<>();
        IPage<SysOss> pageList = sysOssService.page(mpPageConvert.<SysOss>pageParamConvert(params), queryWrapper);
        return R.ok().setData(pageList);
    }

    /**
     * 上传文件
     */
    @PostMapping(value = "/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        // 判断文件
        if (!FilezUtils.isSafeExtension(file.getOriginalFilename())) {
            throw new RuntimeException("只允许上传图片、文档等文件！");
        }
        try {
            //上传文件
            String fileUploadUrl = FilezUtils.upload(file);
            //保存文件信息
            SysOss ossEntity = new SysOss();
            ossEntity.setUrl(fileUploadUrl);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);
            String[] split = fileUploadUrl.split("/");
            return Objects.requireNonNull(R.ok().put("url", fileUploadUrl)).put("name", split[split.length - 1]);
        }catch (Exception e){
            throw new RRException("上传失败", e);
        }
    }

    @GetMapping("/file/{filename}")
    @AuthIgnore
    public ResponseEntity<byte[]> getFile(@PathVariable String filename) throws IOException {
        // 例如：/uploads/abc.jpg
        if (!FilezUtils.exists(filename)) {
            return ResponseEntity.notFound().build();
        }
        byte[] bytes = FilezUtils.readFileToBytes(filename);

        // 根据文件名获取ContentType
        String contentType = null;
        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
            contentType = MediaType.IMAGE_JPEG_VALUE;
        }else{
            // 不支持的文件
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build();
        }
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .body(bytes);
    }



    /**
     * 上传文件
     */
/*
    @AuthIgnore
    @PostMapping(value = "/upload/apk")
    public R uploadApk(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("上传文件不能为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        if (prefix == null || !prefix.equals(".apk")) {
            return R.error("只能上传APK文件");
        }

        TbApkVersion apkVersion = null;
        File tempFile = new File(fileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
            ApkFile apkFile = new ApkFile(tempFile);
            ApkMeta apkMeta = apkFile.getApkMeta();
            apkVersion = new TbApkVersion();
            apkVersion.setVersionCode(Math.toIntExact(apkMeta.getVersionCode()));
            apkVersion.setVersionName(apkMeta.getVersionName());
            apkVersion.setAppName(apkMeta.getLabel());
            apkVersion.setPackageName(apkMeta.getPackageName());
            apkVersion.setFileName(file.getOriginalFilename());
            apkVersion.setMd5Value(DigestUtil.md5Hex(tempFile));
            apkVersion.setFileSize(String.valueOf(tempFile.length()));

            //上传文件
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String url = iCloudStorage.uploadSuffix(file.getBytes(), suffix);

            //保存文件信息
            SysOss ossEntity = new SysOss();
            ossEntity.setUrl(url);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);
            apkVersion.setDownloadUrl(url);


        } catch (Exception e) {
            log.error("文件上传失败:{}", e.getMessage());
            return R.error("文件上传失败");
        }
        tempFile.delete();
        return R.ok().setData(apkVersion);
    }
*/


    /**
     * 删除
     */
    @PostMapping(value = "/delete")
    public R delete(@RequestBody Long[] ids) {
        sysOssService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
